/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.jboss.seam.scxml.impl;

import java.lang.annotation.Annotation;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeanManager;
import org.apache.commons.scxml.SCXMLExecutor;
import org.jboss.seam.scxml.DialogManager;
import org.jboss.solder.beanManager.BeanManagerLocator;
import org.jboss.solder.logging.Logger;

/**
 *
 * @author Waldemar Kłaczyński
 */
public class DialogUtils {

    private static final Logger log = Logger.getLogger(DialogUtils.class);

    public static <T> Set<T> getReferences(final BeanManager manager, final Class<T> type, Annotation... qualifiers) {
        Set<Bean<?>> resolverBeans = manager.getBeans(type, qualifiers);
        if (resolverBeans.isEmpty()) {
            return Collections.emptySet();
        }
        Set<T> refs = new LinkedHashSet<T>();
        for (Bean<?> bean : resolverBeans) {
            CreationalContext<T> context = (CreationalContext<T>) manager.createCreationalContext(bean);
            if (context != null) {
                refs.add((T) manager.getReference(bean, type, context));
            }
        }
        return refs;
    }

    public static <T> Set<T> getReferences(final Class<T> type, Annotation... qualifiers) {
        BeanManager bm = new BeanManagerLocator().getBeanManager();
        return getReferences(bm, type, qualifiers);
    }
    
    
    public static <T> T getReference(Class<T> type, Annotation... qualifiers) {
        BeanManager bm = new BeanManagerLocator().getBeanManager();
        Set<T> references = getReferences(bm, type, qualifiers);
        if (references.size() > 1) {
            throw new IllegalStateException("Multiple References found with configured class [" + type.getName() + "]");
        }
        if (references.isEmpty()) {
            throw new IllegalStateException("No references with type [" + type.getName() + "] was found");
        }
        return references.iterator().next();
    }

    public static SCXMLExecutor getExecutor() {
        DialogManager manager = getReference(DialogManager.class);
        return manager.getExecutor();
    }
}
